package com.woniu.atms.controller.pre;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.woniu.atms.entity.G5Order;
import com.woniu.atms.service.G5OrderService;
import com.woniu.atms.util.Global;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 张奇
 * @title: PayController
 * @projectName g5_atms
 * @description: TODO 支付控制
 * @date 2022/1/24 15:57
 */
@Controller
@RequestMapping("/api/pre/v1/order_pay")
public class PayController {

    @Resource
    private G5OrderService orderService;


    @RequestMapping("/pay")
    public void pay(HttpServletRequest req, HttpServletResponse resp, String orderCode) throws AlipayApiException, IOException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", Global.APP_ID, Global.APP_PRIVATE_KEY, "json", "UTF-8", Global.ALIPAY_PUBLIC_KEY, "RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //获取参数
//        String orderno = req.getParameter("orderNo");
//        String money = req.getParameter("money");

        G5Order order = orderService.queryByOrderNo(orderCode);
        String money=order.getPrice().toString();
        //异步调用
        request.setNotifyUrl("");
        request.setReturnUrl("http://localhost:8080/api/pre/v1/order/pay?id="+order.getId());
//        JSONObject bizContent = new JSONObject();
        System.out.println("===========orderCode:"+orderCode+";money:"+money+"===============");
        String form = "{" +
                "    \"out_trade_no\":\"" + orderCode + "\"  ," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":\"" + money + "\"," +
                "    \"subject\":\"车票\"" +
                "  }";
        System.out.println(form);
        request.setBizContent(form); //填充业务参数
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
}
